package cn.ffcs.security.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import cn.ffcs.base.service.BaseService;
import cn.ffcs.security.dao.UserResourceDAO;
import cn.ffcs.security.model.User;
import cn.ffcs.security.model.UserResource;
import cn.ffcs.security.web.UserContext;
import cn.ffcs.util.context.ApplicationContextUtil;

/**
 * User服务层接口实现<br/>
 * <table>
 * <tr>
 * <td>负责人/principal:</td>
 * <td colspan="2">liuzhh</td>
 * <tr>
 * <td>修改记录/revision:</td>
 * <td colspan="2"></td>
 * </tr>
 * <tr>
 * <td>日期:</td>
 * <td>修改人:</td>
 * <td>修改说明:</td>
 * </tr>
 * <tr>
 * <td></td>
 * <td></td>
 * <td></td>
 * </tr>
 * </table>
 * @author liuzhh
 * @version $Id$
 */
public class UserService<U extends User> extends BaseService<U> implements
        IUserService<U>
{
    
    private UserResourceDAO userResourceDAO;
    private UserContext userContext;
    
    public void saveOrUpdate(U user){
        if (user != null)
        {
            //获取当前数据库时间
            Date date=super.getCurrSysdate();
            if (user.getId() == null || user.getId() == 0)
            {   
                //设置操作人
                user.setCreator("admin");
                //设置用户信息
                user.setLastLoginTime(date);
                user.setLastModifyTime(date);
                user.setLastUpdateTime(date);
                //设置有效时间
                user.setBegin(date);
                Long l=Long.valueOf("9783941568000");
                Date end=new Date(l);
                user.setEnd(end);
                //保存数据
                super.save(user);
            }
            else
            {
                //设置用户信息
                user.setLastUpdateTime(date);
                super.update(user);
            }
        }
    }
    
    /**
     * 
     * 校验用户名和密码
     * @param username
     * @param password
     * @return
     */
    public boolean validUser(String username,String password){
        
        Criterion cond1=Restrictions.gt("userID", username);
        Criterion cond2=Restrictions.gt("password", password);
        Criterion cond=Restrictions.and(cond1, cond2);
            
        List<U> result=findBy(cond);
        
        if (result!=null && result.size()>0){
            return true;
        }
        
        return false;
    }
    /**
     * 
     * 校验用户信息
     * @param username
     * @param password
     * @return
     */
    public boolean validUser(U user){
        
        Criterion cond1=Restrictions.gt("userID", user.getUserID());
        Criterion cond2=Restrictions.gt("password", user.getPassword());
        Criterion cond=Restrictions.and(cond1, cond2);
            
        List<U> result=findBy(cond);
        
        if (result!=null && result.size()>0){
            user=result.get(0);
            return true;
        }
        
        return false;
    }

    /**
     * 校验用户信息 返回值： 1：操作成功 -1:用户名不存在 -2:用户名和密码不匹配或密码不正确
     * @param username
     * @param password
     * @return
     */
    public int checkUser(U user)
    {

        Criterion cond1 = Restrictions.eq("userID", user.getUserID());
        Criterion cond2;
        //判斷是密碼認證還是MISKEY認證
        if (StringUtils.isNotEmpty(user.getMisKey())){     
            cond2 = Restrictions.eq("misKey", user.getMisKey()); 
        }else{ 
            cond2 = Restrictions.eq("password", user.getPassword());                 
        }
        
        Criterion cond = Restrictions.and(cond1, cond2);
        
        //校验用户是否已存在
        List<U> result = findBy(cond1);
        if (result.isEmpty())
        {
            return -1;
        }
        
        //校验用户和密码是否匹配或者與MISKEY是否匹配
        result = findBy(cond);
        if (result != null && result.size() > 0)
        {
            copyUser(result.get(0),user);
            user = result.get(0);
            //获取用户权限资源信息，并初始化
            UserContext uc=new UserContext();
            uc.setCurrUser(user);
            //获取用户权限资源列表
            Criterion c = Restrictions.eq("userID", user.getUserID());
            List<UserResource> userResources=userResourceDAO.findBy(c);
            uc.setUserResources(userResources);
            if (userResources!=null){
                Map<String,UserResource> dispRsc=new HashMap<String,UserResource>();
                for (UserResource ur:userResources){
                    dispRsc.put(ur.getResourceType()+ur.getKey(), ur);
                }
                uc.setDispatchResources(dispRsc);
            }
            //获取用户菜单权限资源列表
            Criterion c1 = Restrictions.eq("userID", user.getUserID());
            Criterion c2 = Restrictions.eq("resourceType", "MENU");
            Criterion c3 = Restrictions.and(c1, c2);
            List<UserResource> menus=userResourceDAO.findByAndOrder(c3,"disport","ASC");
            uc.setMenus(menus);
            //获取各模块菜单资源
//            Criterion M1 = Restrictions.eq("userID", user.getUserID());
//            Criterion M2 = Restrictions.eq("resourceType", "MODEL_MENU");
//            Criterion M3 = Restrictions.and(M1, M2);
//            List<UserResource> modelMenus=userResourceDAO.findByAndOrder(M3,"disport","ASC");
//            uc.setModelMenus(modelMenus);
            
            userContext=uc;
                        
            return 1;
        }
        else
        {
            return -2;
        }
    }
    
    private void copyUser(U sour,U obj){
        if(sour!=null&&obj!=null){
            obj.setId(sour.getId());
            obj.setPerson(sour.getPerson());
        }
    }

    /**
     * @return the userResourceDAO
     */
    public UserResourceDAO getUserResourceDAO()
    {
        return userResourceDAO;
    }

    /**
     * @param userResourceDAO the userResourceDAO to set
     */
    public void setUserResourceDAO(UserResourceDAO userResourceDAO)
    {
        this.userResourceDAO = userResourceDAO;
    }

    /**
     * @return the userContext
     */
    public UserContext getUserContext()
    {
        return userContext;
    }

    /**
     * @param userContext the userContext to set
     */
    public void setUserContext(UserContext userContext)
    {
        this.userContext = userContext;
    }
    
}
